package org.xhnews.parsers;

import java.io.InputStream;

import org.xhnews.log.RaspberryLogger;
import org.xhnews.to.Version;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class VersionPullXMLParser {
	// 解析频道列表
	public static Version readVersion(InputStream inputStream,
			String inputEncoding) {
		try {
			// 创建Pull解析
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance();
			XmlPullParser pullParser = pullParserFactory.newPullParser();
			// 解析XML
			pullParser.setInput(inputStream, inputEncoding);
			// 开始
			int eventType = pullParser.getEventType();
			Version ver = null;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String nodeName = pullParser.getName();
				switch (eventType) {
				// 文档开始
				case XmlPullParser.START_DOCUMENT:
					ver = new Version();
					break;
				// 节点开始
				case XmlPullParser.START_TAG:
					if ("latest".equals(nodeName)) {
						String id = pullParser.getAttributeValue(null, "ver");
						String url = pullParser.getAttributeValue(null, "url");
						String description = pullParser.getAttributeValue(null,
								"description");
						ver.setID(id);
						ver.setUrl(url);
						ver.setDescription(description);
					}
					break;
				// 节点结束
				case XmlPullParser.END_TAG:
					break;
				}
				eventType = pullParser.next();
			}
			if (ver.getID().equals("")) {
				return null;
			} else
				return ver;
		} catch (Exception e) {
			RaspberryLogger.getInstance().info(e.getMessage());
			return null;
		}
	}
}
